package com.example.demo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;


public class StaticFileServer4 {
    private static final String WEB_ROOT = "C:\\Users\\32398\\Desktop\\openapi2\\"; // 替换为实际的静态文件目录

    public static void main(String[] args) throws IOException {
        int port = 8082;
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("服务器已启动，监听端口：" + port);

        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(new RequestHandler(socket)).start();
        }
    }
}

class RequestHandler implements Runnable {
    private Socket socket;

    public RequestHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String line = reader.readLine();
            String filePath = "C:\\Users\\32398\\Desktop\\openapi2\\index.html";

            if (line != null && line.contains("GET")) {
                filePath = line.split(" ")[1];
            }

            if (!filePath.equals("/")) {
                filePath = filePath.substring(1);
            } else {
                filePath = "index.html";
            }
            filePath = "C:\\Users\\32398\\Desktop\\openapi2\\index.html";
            File file = new File(filePath);
            if (file.exists()) {
                OutputStream outputStream = socket.getOutputStream();
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println("HTTP/1.1 200 OK");
                writer.println("Content-Type: text/html");
                writer.println("Content-Length: " + file.length());
                writer.println();

                FileInputStream fis = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                fis.close();
            } else {
                OutputStream outputStream = socket.getOutputStream();
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println("HTTP/1.1 404 Not Found");
                writer.println("Content-Type: text/html");
                writer.println();
                writer.println("<h1>404 Not Found</h1>");
            }

            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
